<template>
    <header>
        <div class="container">
            <nav>
                <ul class="nav_links">
                    <li><h2>爱编程</h2></li>
                    <li>
                        <router-link to="/">首页</router-link>
                    </li>
                    <li>
                        <router-link to="/rankings">排行榜</router-link>
                    </li>
                    <li>
                        <router-link to="/tags">标签</router-link>
                    </li>
                    <li v-if="userStore.role === 3">
                        <router-link to="/user-list">用户管理</router-link>
                    </li>
                    <li v-if="userStore.role >= 2">
                        <router-link to="/question-list">问题管理</router-link>
                    </li>
                </ul>
            </nav>
            <div class="search">
                <n-input v-model:value="questionStore.keyword" :autosize="true" :clearable="true" placeholder="搜索"
                         style="min-width: 250px; margin-right: 30px;" @keyup.enter="handleSearch">
                    <template #suffix>
                        <n-icon :component="Search"/>
                    </template>
                </n-input>
                <n-dropdown v-if="isLogin" :options="options" trigger="click">
                    <n-avatar
                        :round="true"
                        :size="35"
                        :style="{color: 'white', backgroundColor: 'orange', fontSize: '18px', cursor: 'pointer'}"
                    >{{ userStore.username.toString().substring(0, 1) }}
                    </n-avatar>
                </n-dropdown>
                <n-button v-else :ghost="true" type="primary" @click="showModal=true">登录</n-button>
            </div>
            <n-modal v-model:show="showModal" :style="bodyStyle" preset="card" title="登录注册">
                <n-card
                    :bordered="false"
                    aria-modal="true"
                    role="dialog"
                >
                    <n-tabs v-model:value="tabValue" justify-content="space-evenly" size="large">
                        <n-tab-pane name="signin" tab="登录">
                            <n-form ref="loginFormRef" :model="loginForm" :rules="loginRules">
                                <n-form-item-row label="学号" path="account">
                                    <n-input v-model:value="loginForm.account" size="large"/>
                                </n-form-item-row>
                                <n-form-item-row label="密码" path="password">
                                    <n-input v-model:value="loginForm.password" size="large" type="password"/>
                                </n-form-item-row>
                            </n-form>
                            <n-button :block="true" :secondary="true" :strong="true" size="large" type="primary"
                                      @click="handleLogin">
                                登录
                            </n-button>
                        </n-tab-pane>
                        <n-tab-pane name="signup" tab="注册">
                            <n-form ref="registerFormRef" :model="registerForm" :rules="registerRules">
                                <n-form-item label="用户名" path="username">
                                    <n-input v-model:value="registerForm.username" size="large"/>
                                </n-form-item>
                                <n-form-item label="学号" path="account">
                                    <n-input v-model:value="registerForm.account" size="large"/>
                                </n-form-item>
                                <n-form-item label="班级" path="classNumber">
                                    <n-input v-model:value="registerForm.classNumber" size="large"/>
                                </n-form-item>
                                <n-form-item label="密码" path="password">
                                    <n-input v-model:value="registerForm.password" size="large" type="password"
                                             @input="handlePasswordInput"/>
                                </n-form-item>
                                <n-form-item ref="rPasswordFormItemRef" :first="true" label="重复密码"
                                             path="reenteredPassword">
                                    <n-input v-model:value="registerForm.reenteredPassword"
                                             :disabled="!registerForm.password" size="large"
                                             type="password"/>
                                </n-form-item>
                            </n-form>
                            <n-button :block="true" :secondary="true" :strong="true" size="large"
                                      type="primary" @click="handleRegister">
                                注册
                            </n-button>
                        </n-tab-pane>
                    </n-tabs>
                </n-card>
            </n-modal>
        </div>
    </header>
</template>

<script setup>
import { NIcon, useMessage } from 'naive-ui'
import { computed, h, ref } from 'vue'
import { Edit, Search, SignOutAlt, UserCircle } from '@vicons/fa'
import { useUserStore } from '../store/user'
import { login } from '../api/login'
import { removeSession, saveSessionObject } from '../utils/storage'
import { registerUser } from '../api/user'
import { useRouter } from 'vue-router'
import { useQuestionStore } from '../store/question'
import { getCurrentUserId } from '../utils/mini-lodash'

const renderIcon = (icon) => {
    return () => {
        return h(NIcon, null, {
            default: () => h(icon),
        })
    }
}
const userStore = useUserStore()
const router = useRouter()
const message = useMessage()
const loginForm = ref({
    account: '',
    password: '',
})
const registerForm = ref({
    account: '',
    username: '',
    classNumber: '',
    password: '',
    reenteredPassword: '',
})
const tabValue = ref('signin')
let showModal = ref(false)
const bodyStyle = ref({
    width: '25%',
})
const registerFormRef = ref(null)
const rPasswordFormItemRef = ref(null)
const loginFormRef = ref(null)
const isLogin = computed(() => {
        return userStore.token !== ''
    },
)
const handlePasswordInput = () => {
    if (registerForm.value.reenteredPassword) {
        rPasswordFormItemRef.value?.validate({ trigger: 'password-input' })
    }
}
const validatePasswordStartWith = (rule, value) => {
    return !!registerForm.value.password && registerForm.value.password.startsWith(value) &&
        registerForm.value.password.length >= value.length
}
const validatePasswordSame = (rule, value) => {
    return value === registerForm.value.password
}
const registerRules = {
    account: {
        required: true,
        message: '请输入学号',
        trigger: 'blur',
    },
    password: [
        {
            required: true,
            message: '请输入密码',
        },
    ],
    reenteredPassword: [
        {
            required: true,
            message: '请再次输入密码',
            trigger: ['input', 'blur'],
        },
        {
            validator: validatePasswordStartWith,
            message: '两次密码输入不一致',
            trigger: 'input',
        },
        {
            validator: validatePasswordSame,
            message: '两次密码输入不一致',
            trigger: ['blur', 'password-input'],
        },
    ],
}
const loginRules = {
    account: {
        required: true,
        message: '请输入学号',
        trigger: 'blur',
    },
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
        },
    ],
}
const handleLogout = () => {
    removeSession('user')
    userStore.LOGOUT()
    message.success('已登出')
    router.push('/')
}
const handleLogin = () => {
    loginFormRef.value?.validate((errors) => {
            if (!errors) {
                login(loginForm.value).then(res => {
                    if (res.code === '200') {
                        saveSessionObject('user', res.data)
                        userStore.LOGIN(res.data)
                        message.success('登录成功')
                        showModal.value = false
                    } else {
                        message.error('用户名或密码错误')
                        showModal.value = true
                    }
                })
            } else {
                message.error('验证失败')
            }
        },
    )
}
const handleRegister = () => {
    registerFormRef.value?.validate((errors) => {
            if (!errors) {
                registerUser(registerForm.value).then(res => {
                        message.success('注册成功')
                        setTimeout(() => {
                            tabValue.value = 'signin'
                        }, 1e3)
                    },
                )
            } else {
                message.warning('注册失败')
            }
        },
    )

}
const handleClickProfile = () => {
    router.push({
        name: 'User',
        params: { id: getCurrentUserId() },
    })
}
const handleEditProfile = () => {
    router.push({
        name: 'EditProfile',
        params: { id: getCurrentUserId() },
    })
}
const options = [
    {
        label: '个人主页',
        key: 'profile',
        icon: renderIcon(UserCircle),
        props: {
            onClick: handleClickProfile,
        },
    },
    {
        label: '编辑用户资料',
        key: 'editProfile',
        icon: renderIcon(Edit),
        props: {
            onClick: handleEditProfile,
        },
    },
    {
        label: '退出登录',
        key: 'logout',
        icon: renderIcon(SignOutAlt),
        props: {
            onClick: handleLogout,
        },
    },
]

const questionStore = useQuestionStore()
const handleSearch = () => {
    router.push({
        name: 'Search',
        params: {
            keyword: questionStore.keyword,
        },
    })
    questionStore.loading = true
}
</script>

<style scoped>
header {
    /*position: sticky;*/
    top: 0;
    background-color: #fff;
    box-shadow: 0 1px 0 rgb(26 26 26 / 10%);
    white-space: nowrap;
    height: 60px;
}

.n-card :deep(.n-card__content:first-child), .n-card :deep(.n-card__footer:first-child) {
    padding-top: 0;
}

header .container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
}

.nav_links {
    list-style: none;
    display: flex;
    align-items: center;
}

.nav_links li {
    display: inline-block;
    padding: 0 16px;
}

.nav_links li a {
    transition: all 0.3s ease 0s;
}

.nav_links li a:hover {
    color: #36ad6a;
}

.search {
    display: inline-flex;
    flex-wrap: nowrap;
    vertical-align: bottom;
}

li, a {
    font-family: sans-serif;
    font-weight: 500;
    font-size: 16px;
    color: black;
    text-decoration: none;
}

</style>
